﻿using Microsoft.AspNetCore.Http;
using Vin.Tool.Core.AssemblyCategory;

namespace Vin.Extension.ServerSentEvent.Client;

public static class SseClientInstance
{
    #region 客户端 List

    // private static List<ISseClientAdapter> _sseClients = new();
    //
    // public static void AddClient(ISseClientAdapter client) => _sseClients.Add(client);
    //
    // public static void RemoveClient(ISseClientAdapter client) => _sseClients.Remove(client);
    //
    // public static List<ISseClientAdapter> GetClients() => _sseClients;
    //
    // public static List<ISseClientAdapter> Clients => _sseClients;
    //
    // public static ISseClientAdapter? GetClient(string id) => _sseClients.FirstOrDefault(m => m.Id == id);

    #endregion

    #region 客户端 Dict

    private static Dictionary<string, ISseClientAdapter> _sseClientDict = new();

    public static void AddClient(ISseClientAdapter client)
    {
        if (_sseClientDict.ContainsKey(client.Id))
        {
            _sseClientDict[client.Id].DisconnectAsync().Wait();
        }

        _sseClientDict[client.Id] = client;
    }

    public static void RemoveClient(ISseClientAdapter client) => _sseClientDict.Remove(client.Id);

    public static List<ISseClientAdapter> GetClients() => _sseClientDict.Values.ToList();

    public static List<ISseClientAdapter> Clients => _sseClientDict.Values.ToList();

    public static ISseClientAdapter? GetClient(string id) => _sseClientDict.ContainsKey(id) ? _sseClientDict[id] : null;

    #endregion
}